package com.ctrl.riveradministrator.mvp.view.activity.file_information;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ctrl.riveradministrator.R;
import com.ctrl.riveradministrator.base.BaseActivity;
import com.ctrl.riveradministrator.base.BaseListAdapter;
import com.ctrl.riveradministrator.RaApplication;
import com.ctrl.riveradministrator.common.What;
import com.ctrl.riveradministrator.mvp.model.FileInfo;
import com.ctrl.riveradministrator.mvp.presenter.FileInfoPresenter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileInfoActivity extends BaseActivity<FileInfoPresenter> implements FileInfoView,
        BaseListAdapter.OnItemClickListener<FileInfo> {

    private Toolbar toolbar;
    private TextView titleTv;
    private ImageView leftMenu;

    private RecyclerView infoDynRl;
    private SwipeRefreshLayout infoDynSfl;
    private LinearLayoutManager layoutManager;
    private FileInfoAdapter fileInfoAdapter;

    private List<FileInfo> fileInfos = new ArrayList<>();
    private static int currentPage;

    @Override
    protected void initParams(Bundle parms) {

    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_file_info;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView(View view) {
        toolbar = $(R.id.toolbar);
        titleTv = $(R.id.title_tv);
        leftMenu = $(R.id.left_iv);
        infoDynRl = $(R.id.info_list);
        infoDynSfl = $(R.id.info_srl);

        layoutManager = new LinearLayoutManager(this);
        infoDynRl.setLayoutManager(layoutManager);
        infoDynSfl.setColorSchemeColors(Color.RED, Color.BLUE);
        infoDynSfl.setEnabled(false);
        fileInfoAdapter = new FileInfoAdapter(this);
        infoDynRl.setAdapter(fileInfoAdapter);

        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("加载中...");
        pDialog.setCancelable(false);

        /*
         * 设置toolbar
         * */
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setTitle("");
        titleTv.setText(getString(R.string.file_info));
        leftMenu.setBackground(getDrawable(R.drawable.ic_chevron_left_24dp));
    }

    @Override
    protected void doBusiness(Context mContext) {
        currentPage = 0;
        infoDynRl.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (infoDynRl.computeVerticalScrollExtent() + infoDynRl.computeVerticalScrollOffset()
                            >= infoDynRl.computeVerticalScrollRange()) {
                        currentPage++;
                        mPresenter.getDynInfo(currentPage + "", "20");
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        mPresenter.getDynInfo(currentPage + "", "20");
    }

    @Override
    protected void widgetClick(View view) {
        switch (view.getId()) {
            case R.id.left_iv:
                finish();
                break;
        }
    }

    @Override
    protected void setListener() {
        leftMenu.setOnClickListener(this);
        fileInfoAdapter.setOnItemClickListener(this);
    }

    @Override
    public void handleMessage(Message message, int what) {

    }

    @Override
    protected FileInfoPresenter createPresenter() {
        return new FileInfoPresenter(this);
    }

    @Override
    public void showMessage(List<FileInfo> fileInfos) {
        this.fileInfos.addAll(fileInfos);
        fileInfoAdapter.updateListView(this.fileInfos);
    }

    @Override
    public void onItemClick(FileInfo fileInfo, int position) {
       /* if (isServiceRunning(DownloadService.class.getName())) {
            Toast.makeText(this, "正在下载", Toast.LENGTH_SHORT).show();
            return;
        }
        String downloadUrl = fileInfo.getPath();
        Intent intent = new Intent(this, DownloadService.class);
        Bundle bundle = new Bundle();
        bundle.putString("download_url", downloadUrl);
        bundle.putString("download_file", downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1));
        intent.putExtras(bundle);
        startService(intent);*/
        startActivity(new Intent(this, FileActivity.class).putExtra("fileInfo", fileInfo));
    }


    @Override
    public void showLoading() {
        super.showLoading();
        //pDialog.show();
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
        //pDialog.cancel();
    }

    /**
     * 用来判断服务是否运行.
     *
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    private boolean isServiceRunning(String className) {

        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) this
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(Integer.MAX_VALUE);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }


    private static void openFile(Context context, File f) {
        Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        myIntent.setDataAndType(Uri.fromFile(f), "application/zip");
        context.startActivity(myIntent);
    }

    public static class FileDownloadHandler extends android.os.Handler {
        public FileDownloadHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case What.FILE_DOWNLOADING:
                    Log.d("file", "::f");
                    int i = msg.arg1;
                    Toast.makeText(RaApplication.raApplication, "已下载" + i + "%", Toast.LENGTH_SHORT).show();
                    break;
                case What.FILE_COMPLETED:
                    File file = (File) msg.obj;
                    Toast.makeText(RaApplication.raApplication, "下载完成，请在" + file.getAbsolutePath() + "中查看",
                            Toast.LENGTH_LONG).show();
                    break;
                case What.FILE_ERROR:
                    Toast.makeText(RaApplication.raApplication, "加载失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
}
